package com.mynews.bean;

import android.app.Activity;
import android.widget.TextView;

import androidx.databinding.BindingAdapter;

import com.mynews.utils.BmobApi;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class CollectionBean {
    public String newsId,userId,title,id;
    public CollectionBean(String id,String newsId, String userId){
        this.id=id;
        this.newsId=newsId;
        this.userId=userId;
    }
    @BindingAdapter(value = {"bindTitle","activity"}, requireAll = false)
    public static void getTitle(TextView textView, String newsId, Activity activity){
        BmobApi.get("https://api2.bmob.cn/1/classes/news/"+newsId, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                activity.runOnUiThread(() -> textView.setText("未知标题"));
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                activity.runOnUiThread(() -> {
                    try {
                        assert response.body() != null;
                        JSONObject jo = new JSONObject(response.body().string());
                        if (jo.isNull("error")){
                            textView.setText(jo.getString("title"));
                        }else {
                            textView.setText("未知标题");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }
}